package org.dreamwork.sso.saml2.util;

import java.io.*;
import java.net.URL;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 13-8-28
 * Time: 上午11:24
 */
public class DynamicFromBuilder {
    private String action;
    private Map<String, Object> parameters;

    private static final String template = readTemplate ();

    private static String readTemplate () {
        ClassLoader loader = DynamicFromBuilder.class.getClassLoader ();
        URL url = loader.getResource ("org/dreamwork/sso/saml2/servlet/resource/form-template.html");
        if (url == null)
            throw new RuntimeException ("Can't find restore-form template!");

        ByteArrayOutputStream baos = new ByteArrayOutputStream ();
        InputStream in = null;
        try {
            in = url.openStream ();
            byte[] buff = new byte[1024];
            int length;
            while ((length = in.read (buff)) != -1)
                baos.write (buff, 0, length);
            return baos.toString ("UTF-8");
        } catch (Exception ex) {
            throw new RuntimeException (ex);
        } finally {
            if (in != null) try {
                in.close ();
            } catch (IOException ex) {
                // ignore
            }
        }
    }

    public DynamicFromBuilder () {}
    public DynamicFromBuilder (String action, Map<String, Object> parameters) {
        this.action = action;
        this.parameters = parameters;
    }

    public String getAction () {
        return action;
    }

    public void setAction (String action) {
        this.action = action;
    }

    public Map<String, Object> getParameters () {
        return parameters;
    }

    public void setParameters (Map<String, Object> parameters) {
        this.parameters = parameters;
    }

    public void build (Writer writer) throws IOException {
        String form = template.replace ("${action}", action);
        StringBuilder builder = new StringBuilder ();
        if (parameters != null) for (String key : parameters.keySet ()) {
            Object o = parameters.get (key);
            if (o == null) {
                builder.append ("<input type='hidden' name='").append (key).append ("' value='' />\n");
            } else if (o instanceof String) {
                builder.append ("<input type='hidden' name='").append (key)
                       .append ("' value='").append (o).append ("' />\n");
            } else {
                String[] values = (String[]) o;
                for (String value : values) {
                    builder.append ("<input type='hidden' name='").append (key)
                            .append ("' value='").append (value).append ("' />\n");
                }
            }
        }
        form = form.replace ("${form-body}", builder);
        writer.append (form);
        writer.flush ();
    }
}